<?php include("header_liga_required.php"); ?>

<?php
$connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);
mysql_select_db(DB_CATALOG);

$query = "select club_id from zt_team te 
	join zt_tournament t on t.tournament_id = te.tournament_id
	where t.isCurrent = 1";
$result = mysql_query($query, $connect);

if (mysql_num_rows($result) > 0) {
	rejectIfError(null, "subscribe_teams.php: ploegen zijn reeds klaar voor spelerslijsten");
}

mysql_query("SET AUTOCOMMIT=0", $connect);
mysql_query("BEGIN", $connect);

$query = "select s.*, c.clubname from zt_subscription s
		join zt_tournament t on t.tournament_id = s.tournament_id
		join club c on c.club_id = s.club_id
		where t.isCurrent = 1 order by s.club_id";

$result = mysql_query($query, $connect);
$clubItems = array();
while ($row = mysql_fetch_assoc($result)) {
	$dep1Count = $row['dep1Count'];
	$dep2Count = $row['dep2Count'];
	$dep3Count = $row['dep3Count'];
	
	$teamNr = 0;
	
	for ($i = 1; $i <= $dep1Count; $i++) {
		$teamNr++;
		$query = sprintf("INSERT INTO zt_team (tournament_id, club_id, team_name, team_nr, department_nr)
                VALUES (%d, %d, '%s', %d, %d)",
		$row['tournament_id'], $row['club_id'], $row['clubname'].' '.$teamNr, $teamNr, '1');
		mysql_query($query, $connect);
		rejectTranIfError($query, "subscribe_teams.php: invoeren team in afdeling 1 is mislukt.");
	}
	
	for ($i = 1; $i <= $dep2Count; $i++) {
		$teamNr++;
		$query = sprintf("INSERT INTO zt_team (tournament_id, club_id, team_name, team_nr, department_nr)
                VALUES (%d, %d, '%s', %d, %d)",
		$row['tournament_id'], $row['club_id'], $row['clubname'].' '.$teamNr, $teamNr, '2');
		mysql_query($query, $connect);
		rejectTranIfError($query, "subscribe_teams.php: invoeren team in afdeling 2 is mislukt.");
	}
	
	for ($i = 1; $i <= $dep3Count; $i++) {
		$teamNr++;
		$query = sprintf("INSERT INTO zt_team (tournament_id, club_id, team_name, team_nr, department_nr)
                VALUES (%d, %d, '%s', %d, %d)",
		$row['tournament_id'], $row['club_id'], $row['clubname'].' '.$teamNr, $teamNr, '3');
		mysql_query($query, $connect);
		rejectTranIfError($query, "subscribe_teams.php: invoeren team in afdeling 3 is mislukt.");
	}
}

mysql_query("COMMIT", $connect);

redirect("/tornooien/zt-php/zt.php")
?>

<?php include("footer.php"); ?>